package com.appbee.cm.client.nav.ui;

import java.util.List;

import com.appbee.cm.client.nav.presenter.NavItemWrap;
import com.appbee.cm.client.nav.presenter.SimpleNavPresenter;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;

public class SimpleNav extends Widget implements SimpleNavPresenter.View
{
	private ISimpleNavStyle navStyle;
	private List<NavItemWrap> data;
	private NavItemWrap selectedItem;

	public interface Template extends SafeHtmlTemplates
	{
		@Template("<li class='{0}'><a href='{1}' class='{2}'>{3}</a>")
		SafeHtml item(	String liClazz,
						String href,
						String linkClazz,
						String content);

		@Template("<li class='{0}'><button class='{1}' name='{2}' title='{3}'>{4}</button></li>")
		SafeHtml button(String liClazz,
						String clazz,
						String name,
						String title,
						String value);

	}

	private static final Template TEMPLATE = GWT.create(Template.class);

	public SimpleNav()
	{
		super();
		setElement(DOM.createElement("UL"));
	}

	@Override
	public void setNavStyle(ISimpleNavStyle navStyle)
	{
		this.navStyle = navStyle;
		setStyleName(navStyle.nav());
		render();
	}

	@Override
	public void setData(List<NavItemWrap> data)
	{
		this.data = data;
		render();
	}

	public NavItemWrap getSelectedItem()
	{
		return selectedItem;
	}

	@Override
	public void setSelectedItem(NavItemWrap selectedItem)
	{
		this.selectedItem = selectedItem;
		render();
	}

	private void render()
	{
		// Don't render if navStyle isn't set.
		if (navStyle == null || data == null)
			return;

		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		for (NavItemWrap navItem : data)
		{
			// Create li class
			String liClazz = navStyle.navItem();
			if (navItem == selectedItem)
				liClazz += " " + navStyle.navItemSelected();

			// Append item
			String path = navItem.getPath() == null
					|| navItem.getPath().length() == 0 ? "#" : "#n:"
					+ navItem.getPath();
			sb.append(TEMPLATE.item(liClazz,
									path,
									navStyle.navItemLink(),
									navItem.getName()));
		}

		// set inner html
		getElement().setInnerHTML(sb.toSafeHtml().asString());
	}

}
